<template>
  <el-card shadow="hover" class="mt-20">
    <el-form
      ref="skuFormRef"
      :model="SkuForm"
      label-width="120px"
      :rules="skuRules"
    >
      <el-form-item label="SPU名称" prop="spuName"
        >{{ SkuForm.spuName }}
      </el-form-item>
      <el-form-item label="SkU名称" prop="skuName">
        <el-input
          v-model="SkuForm.skuName"
          placeholder="请输入SKU名称"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item label="价格（元）" prop="prise">
        <el-input-number
          v-model="SkuForm.prise"
          controls-position="right"
          placeholder="价格（元）"
          :min="1"
          :max="10"
          size="small"
          class="sku_input_number"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="重量（kg）" prop="weight">
        <el-input-number
          v-model="SkuForm.weight"
          controls-position="right"
          placeholder="重量（kg）"
          class="sku_input_number"
          :min="1"
          :max="10"
          size="small"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          v-model="SkuForm.skuDesc"
          placeholder="请输入规格描述"
          size="small"
          type="textarea"
          :row="3"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10" class="attr_row">
          <el-col
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="4"
            v-for="(attr, index) in attrList"
          >
            <div class="attr__col-wrap">
              <span class="mr-10 attr_col-title">{{ attr.attrName }}</span>
              <el-select
                placeholder="请选择"
                v-model="SkuForm.skuAttrValueList[index]"
                size="small"
              >
                <el-option
                  :label="attrValue.valueName"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}:`"
                  v-for="attrValue in attr.attrValueList"
                ></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="10" class="attr_row">
          <el-col
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="4"
            v-for="(saleAttr, index) in saleAttrValueList"
          >
            <div class="attr__col-wrap">
              <span class="mr-10 attr_col-title">{{
                saleAttr.saleAttrName
              }}</span>
              <el-select
                placeholder="请选择"
                v-model="SkuForm.skuSaleAttrValueList[index]"
                size="small"
              >
                <el-option
                  :label="saleAttrValue.saleAttrValueName"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}:`"
                  v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                ></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          ref="multipleTable"
          :data="ImageList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="图片" width="350">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" class="addSku_img" />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" width="350">
          </el-table-column>
          <el-table-column label="操作" width="350">
            <template v-slot="{ row }">
              <el-tag type="success" v-if="row.isDefault === '1'">默认</el-tag>

              <el-button
                v-else
                type="primary"
                size="mini"
                @click="setDefaultImage(row)"
                >设置默认图片</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small">保存</el-button>
        <el-button type="default" size="small" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { getAttrInfoListApi } from "@/api/product/attr";
import { getSpuImageListApi, getSpuSaleAttrListApi } from "@/api/product/spu";
import { mapState } from "vuex";
export default {
  name: "AddSku",
  data() {
    // 自定义图片列表校验规则
    const skuImageListValidator = (rule, value, callback) => {
      // 1.图片列表中必须要选择一张图片
      if (!value.length) {
        callback(new Error("至少选择一个图片"));
      }
      // 2.选中图片必须要有默认图片
      if (!value.some((img) => img.isDefault === "1")) {
        callback(new Error("选中图片必须要有默认图片"));
      }
      callback();
    };
    return {
      SkuForm: {
        spuName: "",
        skuName: "",
        prise: undefined,
        weight: undefined,
        skuDesc: "",
        skuAttrValueList: [],
        skuSaleAttrValueList: [],
        skuImageList: [],
        defaultImage: "", //默认图片
      },
      attrList: [],
      saleAttrValueList: [],
      ImageList: [],
      skuRules: {
        skuName: [
          { required: true, message: "请输入sku名称", trigger: "blur" },
        ],
        prise: [{ required: true, message: "请输入价格", trigger: "blur" }],
        weight: [{ required: true, message: "请输入重量", trigger: "blur" }],
        skuDesc: [
          { required: true, message: "请输入sku描述", trigger: "blur" },
        ],
        skuAttrValueList: [
          { required: true, message: "请选择属性值", trigger: "change" },
        ],
        skuSaleAttrValueList: [
          { required: true, message: "请选择销售属性值", trigger: "change" },
        ],
        skuImageList: [{ required: true, validator: skuImageListValidator }],
      },
    };
  },
  computed: {
    ...mapState("category", ["category1Id", "category2Id", "category3Id"]),
    ...mapState("spu", ["spu"]),
  },
  async mounted() {
    const { id, spuName } = this.spu;
    if (!id) return;
    this.SkuForm.spuName = spuName;
    const res = await Promise.allSettled([
      getSpuImageListApi(id),
      getSpuSaleAttrListApi(id),
      getAttrInfoListApi({
        category1Id: this.category1Id,
        category2Id: this.category2Id,
        category3Id: this.category3Id,
      }),
    ]);

    console.log(res);
    const spuImageList = res[0].value.data; 
    // 对数据处理，添加isDefault属性
    spuImageList.forEach((img) => (img.isDefault = "0"));
    // 这样数据就有响应式
    this.ImageList = spuImageList
    this.saleAttrValueList = res[1].value.data;
    this.attrList = res[2].value.data;
  },
  methods: {
    setDefaultImage(row) {
      console.log(row);
      // 对象新增属性没有响应式
      // 思路一：在获取到数据就添加属性，在赋值给data
      //思路二： this.$set( target, key, value ) 要更改的数据源(可以是对象或者数组) 要更改的具体数据 重新赋的值
      this.ImageList.forEach((img) => (img.isDefault = "0"));
      console.log(this.ImageList);
      row.isDefault = "1";
      this.SkuForm.defaultImage = row.imgUrl;
      // 选中图片中有默认图片才清空校验提示
      if (this.SkuForm.skuImageList.some((img) => img === row)) {
        this.$refs.skuFormRef.clearValidate(["skuImageList"]);
      }
    },
    cancel() {
      this.$emit("setIsShow", 1);
    },
    // handleChange(value) {
    //   console.log(value);
    // },
    handleSelectionChange(val) {
      console.log(val);
      this.SkuForm.skuImageList = val;
    },
  },
};
</script>

<style scoped>
.sku_input_number {
  width: 100%;
}
::v-deep .el-input__inner {
  text-align: left;
}
.attr_row {
  width: 100%;
}
.attr_col {
  margin-top: 10px;
}
.addSku_img {
  width: 100px;
}
.attr__col-wrap {
  display: flex;
  margin-bottom: 10px;
}
.attr_col-title {
  flex-grow: 1;
  text-align: right;
}
</style>
